package dut.ir.lxb.weibo.util;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class BaiduEncoder
{
	private String jsFile;
	
	private String jsCode;
	
	private String encoding = "utf-8";
	
	private ScriptEngine scriptEngine;
	
	
	public BaiduEncoder()
	{
		this.init();
	}
	
	public BaiduEncoder(String jsFile)
	{
		this.jsFile = jsFile;
		this.encoding = "utf-8";
		this.init();
	}
	
	public BaiduEncoder(String jsFile, String encoding)
	{
		this.jsFile = jsFile;
		this.encoding = encoding;
		this.init();
	}
	
	public void init()
	{
		if(this.jsFile.trim().length() == 0)
			return;
		this.jsCode = IOUtility.loadTextFile(jsFile, encoding);
		
		ScriptEngineManager sem = new ScriptEngineManager();
		scriptEngine = sem.getEngineByName("javascript");
		
		try
		{
			scriptEngine.eval(jsCode);
		} catch (ScriptException e)
		{
			e.printStackTrace();
		}
		
	}
	
	public String randomGuid()
	{
		String guid = "";
		if (scriptEngine == null) return guid;
		if (scriptEngine instanceof Invocable)
		{
			Invocable invoke = (Invocable) scriptEngine;
			// 调用preprocess方法，并传入两个参数密码和验证码
			
			try
			{
				guid = invoke.invokeFunction("guidRandom").toString();
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		return guid;
		
	}
	
	public String encryptRSAPassword(String pwd, String pubKey)
	{
		String pass = "";
		if (scriptEngine == null) return pass;
		if (scriptEngine instanceof Invocable)
		{
			Invocable invoke = (Invocable) scriptEngine;
			// 调用preprocess方法，并传入两个参数密码和验证码
			
			try
			{
				pass = invoke.invokeFunction("PasswordEncrypt", pwd, pubKey).toString();
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		return pass;
	}
	
	
	
	
	
	
	
}
